//
//  DisherType.m
//  Recipe
//
//  Created by bing han on 12-7-20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DisherType.h"
#import "DBOptions.h"

@implementation DisherType
static DisherType *instence = nil;
@synthesize parentDisherType = _parentDisherType, allDisherType = _allDisherType;

+(DisherType *) newInstence{
    @synchronized(self){
        if (instence == nil) {
            instence = [[DisherType alloc] init];
            [instence initDisherType];
        }
    }
    return instence;
}

+(id) allocWithZone:(NSZone *)zone{
    @synchronized(self){
        if (instence == nil) {
            instence = [super allocWithZone:zone];
            return instence;
        }
    }
    return nil;
}

-(id) copyWithZone:(NSZone *)zone{
    return self;
}

-(id) retain{
    return self;
}

-(unsigned) retainCount{
    return UINT_MAX;
}

-(id) autorelease{
    return self;
}

-(void) initDisherType{
    DBOptions *dbOption = [DBOptions newInstence];
    FMDatabase *fmdb = dbOption.fmdatabase;
    _parentDisherType = [[NSMutableArray alloc] init];
    
    FMResultSet *rstype = [fmdb executeQuery:@"select * from type where parentkey='' order by parentkey"];
    while ([rstype next]) {
        NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
        [result setValue:[rstype objectForColumnName:@"key"] forKey:@"key"];
        [result setValue:[rstype objectForColumnName:@"parentkey"] forKey:@"parentkey"];
        [result setValue:[rstype objectForColumnName:@"typecn"] forKey:@"typecn"];
        [result setValue:[rstype objectForColumnName:@"typeen"] forKey:@"typeen"];
        
        [_parentDisherType addObject:result];
    }
    
    _allDisherType = [[NSMutableDictionary alloc] init];
    NSDictionary *type = nil;
    for (int i = 0; i< [_parentDisherType count]; i ++) {
        type = [_parentDisherType objectAtIndex:i];
        NSString *key = [type objectForKey:@"key"];
        FMResultSet *rstype = [fmdb executeQuery:@"select * from type where parentkey=? order by parentkey",key];
        NSMutableArray *subArray = [[NSMutableArray alloc] init];
        while ([rstype next]) {
            NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
            [result setValue:[rstype objectForColumnName:@"key"] forKey:@"key"];
            [result setValue:[rstype objectForColumnName:@"parentkey"] forKey:@"parentkey"];
            [result setValue:[rstype objectForColumnName:@"typecn"] forKey:@"typecn"];
            [result setValue:[rstype objectForColumnName:@"typeen"] forKey:@"typeen"];
            [subArray addObject:result];
        }
        [_allDisherType setObject:subArray forKey:key];
        [key release];
        [subArray release];
    }
    [dbOption closeDatabase];
    
    [dbOption closeDatabase];
}
@end
